<?php

namespace App\Http\Controllers;

use App\utils\AesUtils;
use App\utils\RsaUtils;
use Illuminate\Http\Request;

class BaseController extends Controller
{
    private $token;
    private $aesKey;

    public function analysisArgs(Request $request)
    {
        $token = $request->input('token', '');
        $sign = $request->input('sign', '');
        $data = $request->input('data', '');
        $method = $request->input('method', '');
        $time = $request->input('time', '');
        if (!$token || $sign || $data || $method || $time) {
            //todo 待判断那种参数出问题
        }
        $this->token = $token;
        return 0;   //表示无任何问题
    }

    public function decrypt($sign, $data)
    {
        $sign = RsaUtils::privateDecrypt($sign);
        $this->aesKey = $sign;  //获取aes密匙
        $data = AesUtils::decrypt($data, $sign);
        return $data;
    }

    public function response($code, string $data, $msg)
    {
        return [
            'code' => $code,
            'token' => $this->token,
            'sign' => RsaUtils::setSign($data), //密钥生成签名
            'data' => AesUtils::encrypt($data, $this->aesKey), //aes加密
            'msg' => $msg,
            'time' => time()
        ];
    }

    public function error($code)
    {
        switch ($code) {
            case 1000:
                $msg = 'token过期';
                break;
            default:
                $msg = '未知错误!';
        }
        return $this->response($code, ' ', $msg);
    }

}
